1 module hunt.cache.l2cache;
2 
3 import hunt.cache.memory;
4 import hunt.cache.nullable;
5 
6 final class L2Cache(T)
7 {
8 	Nullable!V get(V)(string key)
9 	{
10 		synchronized(this){
11 			auto v1 = _memory.get!V(key);
12 			if(!v1.isnull)
13 				return v1;
14 
15 			auto v2 = _cache.get!V(key);
16 			if(v2.isnull)
17 				return v2;
18 
19 			_memory.put!V(key , v2.origin);
20 
21 			return v2;
22 		}
23 	}
24 
25 	Nullable!V[string] getall(V)(string[] keys)
26 	{
27 		synchronized(this){
28 			Nullable!V[string] mapv;
29 			foreach(k ; keys)
30 			{
31 				mapv[k] = get!V(k);
32 			}
33 
34 			return mapv;
35 		}
36 	}
37 
38 	bool containsKey(string key)
39 	{
40 		synchronized(this){
41 			return _cache.containsKey(key);
42 		}
43 	}
44 	
45 	void put(V)(string key ,  V v , uint expired = 0)
46 	{
47 		synchronized(this){
48 			_cache.put!V(key , v  , expired);
49 			_memory.put!V(key , v , expired);
50 		}
51 	}
52 
53 	bool putifAbsent(V)(string key ,  V v)
54 	{
55 		synchronized(this){
56 			if( _cache.putifAbsent!V(key , v))
57 			{
58 				_memory.put!V(key ,v);
59 				return true;
60 			}
61 		}
62 
63 		return false;
64 	}
65 
66 	void putAll(V)( V[string] maps , uint expired = 0)
67 	{
68 		synchronized(this){
69 			_cache.putAll!V(maps , expired);
70 			_memory.putAll!V(maps , expired);
71 		}
72 	}
73 	
74 	bool remove(string key)
75 	{
76 		synchronized(this){
77 			auto ret = _cache.remove(key);
78 			_memory.remove(key);
79 			return ret;
80 		}
81 	}
82 
83 	void removeAll(string[] keys)
84 	{
85 		synchronized(this){
86 			 _cache.removeAll(keys);
87 			_memory.removeAll(keys);
88 		}
89 	}
90 	
91 	void clear()
92 	{
93 		synchronized(this){
94 		 	_cache.clear();
95 			_memory.clear();
96 		}
97 	}
98 
99 	this(ARG ...)(ARG arg)
100 	{
101 		_memory = new MemoryCache();
102 		_cache = new T(arg);
103 	}
104 
105 private:
106 	MemoryCache _memory;
107 	T			_cache;
108 }